package com.live.shop.home.keyword;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.aliyun.AliyunTtsUtil;
import com.live.shop.home.AudioFileListActivity;
import com.live.shop.home.setting.PermissionActivity;
import com.live.shop.model.AudioFileModel;
import com.live.shop.model.KeywordModel;
import com.live.shop.model.KeywordRecordModel;
import com.live.shop.model.UserModel;
import com.live.shop.sql.KeywordListDatabase;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.FileUtils;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.TtsMessageEvent;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.view.ToastBottomUtils;
import com.live.shop.view.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class AddKeywordActivity extends BaseActivity {
    ImageButton add_keyword_back;
    TextView add_keyword_title;
    EditText add_keyword_input_question;
    EditText add_keyword_input_key;
    RecyclerView add_keyword_recyclerview;
    TextView add_keyword_add;
    TextView add_keyword_save;

    //播放器
    MediaPlayer mediaPlayer;
    //录音
    MediaRecorder mediaRecorder;
    UserModel userModel;
    boolean isPlaying = false;//播放状态
    int PlayingPosition = -1;//播放选择坐标
    //数据类型
    int DataType = 0;
    //录音选择坐标
    int sound_position = -1;
    
    //录音状态
    boolean sound_status = false;

    KeywordListDatabase keyDb;
    UserDatabase userDb;
    KeywordModel keywordModel;
    List<KeywordRecordModel> list;
    String fileDir="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_keyword);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);
        //首先要在你要接受EventBus的界面注册，这一步很重要
        EventBus.getDefault().register(this);

        keyDb = new KeywordListDatabase(getApplicationContext());
        userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();

        add_keyword_back = findViewById(R.id.add_keyword_back);
        add_keyword_title = findViewById(R.id.add_keyword_title);
        add_keyword_input_question = findViewById(R.id.add_keyword_input_question);
        add_keyword_input_key = findViewById(R.id.add_keyword_input_key);
        add_keyword_recyclerview = findViewById(R.id.add_keyword_recyclerview);

        add_keyword_add = findViewById(R.id.add_keyword_add);
        add_keyword_save = findViewById(R.id.add_keyword_save);

        add_keyword_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //添加
        add_keyword_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.add(new KeywordRecordModel("",0,0,"",1));
                adapter.notifyDataSetChanged();
            }
        });

        add_keyword_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 移除当前Activity中所有视图的焦点，保证数据已存储
                clearFocusFromAllViews(findViewById(android.R.id.content));

                if(add_keyword_input_question.getText().toString().isEmpty()){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请填写问题！");
                    return;
                }
                if(add_keyword_input_key.getText().toString().isEmpty()){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请填写关键词！");
                    return;
                }
                if(list.size() == 0){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请添加回复！");
                    return;
                }
                for (KeywordRecordModel recordModel:list) {
                    if(recordModel.getAnswerState() == 0) {
                        ToastBottomUtils.Setinfo(getApplicationContext(),"每条必须有回复音频！");
                        return;
                    }
                }
                if(DataType == 0){
                    //新增
                    keywordModel = new KeywordModel();
                    keywordModel.setQuestion(add_keyword_input_question.getText().toString());
                    keywordModel.setKeyword(add_keyword_input_key.getText().toString());
                    keywordModel.setListRecord(list);
                    keyDb.insertData(keywordModel);
                }else{
                    //编辑
                    keywordModel.setQuestion(add_keyword_input_question.getText().toString());
                    keywordModel.setKeyword(add_keyword_input_key.getText().toString());
                    keywordModel.setListRecord(list);
                    keyDb.updateData(keywordModel);
                }
                ToastUtils.Setinfo(getApplicationContext(),"保存成功",1);
                finish();
            }
        });

        fileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)+"/zhiboMusic";
        File folder = new File(fileDir);
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                // 文件夹创建失败
                ToastUtils.Setinfo(getApplicationContext(),"无法创建文件夹！",2);
            }
        }
        SetListMyValue();
    }
    //加载数据
    private void SetListMyValue() {
        DataType = getIntent().getIntExtra("type",0);
        if(DataType == 1){
            keywordModel = (KeywordModel) getIntent().getSerializableExtra("data");
            list = keywordModel.getListRecord();
            add_keyword_title.setText("编辑关键词");
            add_keyword_input_question.setText(keywordModel.getQuestion());
            add_keyword_input_key.setText(keywordModel.getKeyword());
        }else{
            list = new ArrayList<>();
            list.add(new KeywordRecordModel("",0,0,"",1));
        }

        adapter = new MyAdapter();
        add_keyword_recyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        add_keyword_recyclerview.setAdapter(adapter);
    }
    private MyAdapter adapter;
    class MyAdapter extends RecyclerView.Adapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder holder = new MyAdapter.MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_answer, parent, false));
            return holder;
        }
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            MyViewHolder mholder = (MyAdapter.MyViewHolder) holder;
            KeywordRecordModel keywordRecordModel = list.get(position);

            if(keywordRecordModel.getAnswerState() != 0){
                //【试听】可点击和显示
                mholder.item_answer_sound_listen.setEnabled(true);
                mholder.item_answer_sound_listen.setVisibility(View.VISIBLE);
            }else{
                //【试听】不可点击和隐藏
                mholder.item_answer_sound_listen.setEnabled(false);
                mholder.item_answer_sound_listen.setVisibility(View.INVISIBLE);
            }
            //录音
            if(sound_status && sound_position == position){
                //【开始录音】不可点击和隐藏
                mholder.item_answer_sound_start.setEnabled(false);
                mholder.item_answer_sound_start.setVisibility(View.INVISIBLE);
                //【停止录音】可点击和显示
                mholder.item_answer_sound_stop.setEnabled(true);
                mholder.item_answer_sound_stop.setVisibility(View.VISIBLE);
            }else{
                //【开始录音】可点击和显示
                mholder.item_answer_sound_start.setEnabled(true);
                mholder.item_answer_sound_start.setVisibility(View.VISIBLE);
                //【停止录音】不可点击和隐藏
                mholder.item_answer_sound_stop.setEnabled(false);
                mholder.item_answer_sound_stop.setVisibility(View.INVISIBLE);
            }
            if(PlayingPosition == position){
                mholder.item_answer_sound_listen.setText("停止试听");
            }else{
                mholder.item_answer_sound_listen.setText("试听");
            }
            mholder.item_answer_index.setText(String.valueOf(position+1));
            mholder.item_answer_editText.setText(keywordRecordModel.getAnswerTxt());
            mholder.item_answer_type.setText(GetUtil.voiceType(keywordRecordModel.getAnswerType()));
            mholder.item_answer_status.setText(GetUtil.voiceState(keywordRecordModel.getAnswerState()));
            //删除
            mholder.item_answer_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    notifyItemRemoved(position);
                    keyDb.deleteRecordData(list.get(position).getId());
                    list.remove(position);

                    List<KeywordRecordModel> demoList = new ArrayList<>();
                    for (KeywordRecordModel m:list) {
                        demoList.add(m);
                    }
                    list.clear();
                    list.addAll(demoList);
                    notifyDataSetChanged();
                }
            });
            //试听
            mholder.item_answer_sound_listen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(!FileUtils.getFileExist(getApplicationContext(),keywordRecordModel.getAnswerAudio())){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"音频文件不存在！");
                        return;
                    }
                    if(isPlaying){
                        //播放中，则取消播放
                        isPlaying = false;
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        if(PlayingPosition == position){
                            //暂停
                            PlayingPosition = -1;
                            notifyDataSetChanged();
                            return;
                        }
                    }
                    if(PlayingPosition != position){
                        //开始播放
                        isPlaying = true;
                        PlayingPosition = position;
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        try {
                            mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(keywordRecordModel.getAnswerAudio()));
                            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mediaPlayer) {
                                    mediaPlayer.release();
                                    isPlaying = false;
                                    PlayingPosition = -1;
                                    notifyDataSetChanged();
                                }
                            });
                            mediaPlayer.prepare();
                            mediaPlayer.start();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    notifyDataSetChanged();
                }
            });
            //开始录音
            mholder.item_answer_sound_start.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【麦克风】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                    //文件路径
                    String outputFile = fileDir+"/luyin_"+DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".mp3";
                    mediaRecorder = new MediaRecorder();
                    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
                    mediaRecorder.setOutputFile(outputFile);
                    try {
                        mediaRecorder.prepare();
                        mediaRecorder.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //回答音频
                    list.get(position).setAnswerAudio(outputFile);
                    sound_position = position;
                    sound_status = true;
                    notifyDataSetChanged();
                }
            });
            //停止录音
            mholder.item_answer_sound_stop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(mediaRecorder != null){
                        mediaRecorder.stop();
                        mediaRecorder.release();
                        mediaRecorder = null;
                    }
                    if(keywordRecordModel.getAnswerType() != 0 && keywordRecordModel.getAnswerType() != 3 && DataType == 1){
                        //编辑模型并且不是本地音频和无音频
                        list.get(position).setDeleteStatus(2);//删除状态 1新增 2编辑 3删除
                    }

                    //合成方式 0.暂无 1.录音 2.AI合成 3.本地音频
                    list.get(position).setAnswerType(1);
                    //合成状态 0.暂无 1.已录音 2.已合成 3.已选择
                    list.get(position).setAnswerState(1);
                    sound_position = -1;
                    sound_status = false;

                    notifyDataSetChanged();
                }
            });
            //音频合成
            mholder.item_answer_sound_ai.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String answer = mholder.item_answer_editText.getText().toString();
                    if(answer.isEmpty()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请填写回复内容！");
                        return;
                    }
                    if(answer.length() > 300){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"回复内容超过300字符");
                        return;
                    }
                    list.get(position).setAnswerTxt(answer);

                    if(userModel.getAliyunAccessKeyID().isEmpty() || userModel.getAliyunAppkey().isEmpty() || userModel.getAliyunAccessKeySecret().isEmpty()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请先配置阿里云密钥！");
                        return;
                    }
                    if(userModel.getAliyunVoiceSelect().isEmpty() || userModel.getAliyunFontName().isEmpty()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请选择保存阿里云音色！");
                        return;
                    }
                    //实例化tts
                    if(GetUtil.getUtf8CharsNum(answer) > 300){
                        ToastUtils.Setinfo(getApplicationContext(),"文本长度大于300字符",2);
                        return ;
                    }
                    //文件路径
                    String outputFile = fileDir+"/ai_"+DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".mp3";

                    //语音合成
                    AliyunTtsUtil ttsUtil = new AliyunTtsUtil(userModel.getAliyunAppkey(),userModel.getAliyunAccessKeyID(),userModel.getAliyunAccessKeySecret());
                    //文本、保存文件名
                    ttsUtil.postRequest(getApplicationContext(),answer,outputFile);

                    if(keywordRecordModel.getAnswerType() != 0 && keywordRecordModel.getAnswerType() != 3 && DataType == 1){
                        //编辑模型并且不是本地音频和无音频
                        list.get(position).setDeleteStatus(2);//删除状态 1新增 2编辑 3删除
                    }
                    //合成方式 0.暂无 1.录音 2.AI合成 3.本地音频
                    list.get(position).setAnswerType(2);
                    //合成状态 0.暂无 1.已录音 2.已合成 3.已选择
                    list.get(position).setAnswerState(2);
                    //回答音频
                    list.get(position).setAnswerAudio(outputFile);

                    notifyDataSetChanged();
                }
            });
            //选择本地音频
            mholder.item_answer_sound_local.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getApplicationContext(), AudioFileListActivity.class);
                    startActivityForResult(intent, position);
                }
            });
            //合成文本
            mholder.item_answer_editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // 处理焦点变化事件
                    if (!hasFocus) {
                        // EditText失去焦点时的处理逻辑
                        list.get(position).setAnswerTxt(mholder.item_answer_editText.getText().toString());
                    }
                }
            });
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public int getItemCount() {
            return list.size();
        }
        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView item_answer_index;
            ImageView item_answer_delete;
            EditText item_answer_editText;
            TextView item_answer_type;
            TextView item_answer_status;
            TextView item_answer_sound_listen;
            TextView item_answer_sound_start;
            TextView item_answer_sound_stop;
            TextView item_answer_sound_ai;
            TextView item_answer_sound_local;
            public MyViewHolder( View itemView) {
                super(itemView);
                item_answer_index = itemView.findViewById(R.id.item_answer_index);
                item_answer_delete = itemView.findViewById(R.id.item_answer_delete);
                item_answer_editText = itemView.findViewById(R.id.item_answer_editText);
                item_answer_type = itemView.findViewById(R.id.item_answer_type);
                item_answer_status = itemView.findViewById(R.id.item_answer_status);
                item_answer_sound_listen = itemView.findViewById(R.id.item_answer_sound_listen);
                item_answer_sound_start = itemView.findViewById(R.id.item_answer_sound_start);
                item_answer_sound_stop = itemView.findViewById(R.id.item_answer_sound_stop);
                item_answer_sound_ai = itemView.findViewById(R.id.item_answer_sound_ai);
                item_answer_sound_local = itemView.findViewById(R.id.item_answer_sound_local);
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                AudioFileModel model = (AudioFileModel) data.getSerializableExtra("model");

                list.get(requestCode).setAnswerAudio(model.getUrl());
                //合成方式 0.暂无 1.录音 2.AI合成 3.本地音频
                list.get(requestCode).setAnswerType(3);
                //合成状态 0.暂无 1.已录音 2.已合成 3.已选择
                list.get(requestCode).setAnswerState(3);
                adapter.notifyDataSetChanged();
            }
        }
    }

    //任意写一个方法，给这个方法一个@Subscribe注解，参数类型可以自定义，但是一定要与你发出的类型相同
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(TtsMessageEvent ttsMessageEvent){
        switch (ttsMessageEvent.getNumber()) {
            case 1://正确
                ToastUtils.Setinfo(this,ttsMessageEvent.getMessage(),1);
                break;
            case 2://异常
                ToastUtils.Setinfo(this,ttsMessageEvent.getMessage(),2);
                break;
            case 3://底部toast
                ToastBottomUtils.Setinfo(this,ttsMessageEvent.getMessage());
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);
        // 释放MediaPlayer资源
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        // 释放mediaRecorder资源
        if (mediaRecorder != null) {
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }
    private void clearFocusFromAllViews(ViewGroup root) {
        for (int i = 0; i < root.getChildCount(); i++) {
            View view = root.getChildAt(i);
            if (view instanceof ViewGroup) {
                clearFocusFromAllViews((ViewGroup) view);
            } else {
                view.clearFocus();
            }
        }
    }
}